import os
import getopt
import subprocess
import ujson as json
from time import sleep
from random import randint
from random import choice
from datetime import timedelta
from subprocess import Popen
from django.conf import settings
from django.db import transaction
from django.db.models import F
from django.db.models import Q
from django.db.models import Sum
from django.db.models import Count

from base import errors
from base import controllers as base_ctl
from account.models import AccountModel
from account.models import UserModel
from account.models import SkillModel
from account.models import GoodsModel
from account.models import PetModel
from account.models import ScriptModel
from account.models import SettingModel
from account.models import DutyModel
from account.controllers.name import gen_name
from utils import time_utils


def create_user(master_id, slave_id, zone, site, password, name):
    '''
    创建用户
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    if user_obj:
        data = {
            'master_id': master_id,
            'slave_id': slave_id,
            'zone': zone,
            'site': site,
            'name': name,
            'password': password,
        }
        base_ctl.update_obj(UserModel, user_obj.id, data)
    else:
        user_obj = UserModel.objects.filter(master_id=master_id, slave_id=slave_id, zone=zone, site=site).first()
        if user_obj:
            raise errors.CommonError('用户已存在')
        if not UserModel.check_choices('zone', zone):
            raise errors.CommonError('分区值不正确')
        if not UserModel.check_choices('site', site):
            raise errors.CommonError('位置值不正确')
        data = {
            'master_id': master_id,
            'slave_id': slave_id,
            'zone': zone,
            'site': site,
            'name': name,
            'password': password,
        }
        base_ctl.create_obj(UserModel, data)


def batch_create_users(master_id, slaves, zone):
    '''
    批量创建角色
    '''
    if not UserModel.check_choices('zone', zone):
        raise errors.CommonError('分区值不正确')
    slaves = json.loads(slaves)
    slaves = slaves.get('gid')
    slave_ids = [d.get('name') for d in slaves]

    account_obj = AccountModel.objects.filter(master_id=master_id).first()
    if not account_obj:
        raise errors.CommonError('请先录入对应的主账号')
    password = account_obj.password

    data_list = []
    query = {
        'master_id': master_id,
        'zone': zone,
    }
    for slave_id in slave_ids:
        query['slave_id'] = slave_id
        query['site'] = UserModel.SITE_LEFT
        left_user_obj = UserModel.objects.filter(**query).first()
        if not left_user_obj:
            data = {
                'master_id': master_id,
                'slave_id': slave_id,
                'zone': zone,
                'site': UserModel.SITE_LEFT,
                'password': password,
            }
            data_list.append(data)
        query['site'] = UserModel.SITE_RIGHT
        right_user_obj = UserModel.objects.filter(**query).first()
        if not right_user_obj:
            data = {
                'master_id': master_id,
                'slave_id': slave_id,
                'zone': zone,
                'site': UserModel.SITE_RIGHT,
                'password': password,
            }
            data_list.append(data)
    base_ctl.create_objs(UserModel, data_list)


def update_user(obj_id, master_id, slave_id, zone, site, password, name, task):
    '''
    编辑用户
    '''
    if not UserModel.check_choices('zone', zone):
        raise errors.CommonError('分区值不正确')
    if not UserModel.check_choices('site', site):
        raise errors.CommonError('位置值不正确')
    obj = base_ctl.get_obj(UserModel, obj_id)
    data = {
        'master_id': master_id,
        'slave_id': slave_id,
        'zone': zone,
        'site': site,
        'name': name,
        'password': password,
        'task': task,
    }
    base_ctl.update_obj(UserModel, obj_id, data)


def delete_user(obj_id, operator=None):
    '''
    删除用户
    '''
    UserModel.objects.filter(id=obj_id).delete()


def get_users(master_id=None, slave_id=None, zone=None, site=None, job=None, min_level=None,
        max_level=None, min_money=None, max_money=None, is_online=None, keyword=None, goods_keyword=None, pet_keyword=None, pet_min_level=None,
        pet_max_level=None, skill_keyword=None, skill_min_level=None, skill_max_level=None, has_work=None,
        page_num=None, page_size=None):
    '''
    获取用户列表
    '''
    base_query = UserModel.objects
    if keyword:
        base_query = base_query.filter(Q(name__icontains=keyword)|
                                       Q(master_id__icontains=keyword)|
                                       Q(job__icontains=keyword))
    if master_id:
        base_query = base_query.filter(master_id=master_id)
    if slave_id:
        base_query = base_query.filter(slave_id=slave_id)
    if zone:
        base_query = base_query.filter(zone=zone)
    if site:
        base_query = base_query.filter(site=site)
    if job:
        base_query = base_query.filter(job=job)
    if min_level:
        base_query = base_query.filter(level__gte=min_level)
    if max_level:
        base_query = base_query.filter(level__lte=max_level)
    if min_money:
        min_money = min_money * 10 * 1000
        user_ids = UserModel.objects.values('id', 'bag_money', 'bank_money').annotate(money=F('bag_money')+F('bank_money')).filter(money__gte=min_money).values_list('id', flat=True).all()
        user_ids = list(set(user_ids))
        base_query = base_query.filter(id__in=user_ids)
    if max_money:
        max_money = max_money * 10 * 1000
        user_ids = UserModel.objects.values('id', 'bag_money', 'bank_money').annotate(money=F('bag_money')+F('bank_money')).filter(money__lte=max_money).values_list('id', flat=True).all()
        user_ids = list(set(user_ids))
        base_query = base_query.filter(id__in=user_ids)
    if goods_keyword:
        user_ids = GoodsModel.objects.filter(Q(name__icontains=goods_keyword)|
                                       Q(sign__icontains=goods_keyword))\
                          .values_list('user_id', flat=True)\
                          .all()
        user_ids = list(set(user_ids))
        base_query = base_query.filter(id__in=user_ids)
    if pet_keyword or pet_min_level or pet_max_level:
        pet_query = PetModel.objects
        if pet_keyword:
            pet_query = pet_query.filter(Q(name__icontains=pet_keyword)|
                                           Q(real_name__icontains=pet_keyword)|
                                           Q(sign__icontains=pet_keyword))
        if pet_min_level:
            pet_query = pet_query.filter(level__gte=pet_min_level)
        if pet_max_level:
            pet_query = pet_query.filter(level__lte=pet_max_level)
        user_ids = pet_query.values_list('user_id', flat=True).all()
        user_ids = list(set(user_ids))
        base_query = base_query.filter(id__in=user_ids)

    if skill_keyword or skill_min_level or skill_max_level:
        skill_query = SkillModel.objects
        if skill_keyword:
            skill_query = skill_query.filter(name__icontains=skill_keyword)
        if skill_min_level:
            skill_query = skill_query.filter(level__gte=skill_min_level)
        if skill_max_level:
            skill_query = skill_query.filter(level__lte=skill_max_level)
        user_ids = skill_query.values_list('user_id', flat=True).all()
        user_ids = list(set(user_ids))
        base_query = base_query.filter(id__in=user_ids)

    if has_work is True:
        from workflow.models import WorkerModel
        user_ids = WorkerModel.objects.values_list('user_id', flat=True).all()
        user_ids = list(set(user_ids))
        base_query = base_query.filter(id__in=user_ids)
    if has_work is False:
        from workflow.models import WorkerModel
        user_ids = WorkerModel.objects.values_list('user_id', flat=True).all()
        user_ids = list(set(user_ids))
        base_query = base_query.exclude(id__in=user_ids)

    now = time_utils.now()
    if is_online == 1:
        base_query = base_query.filter(dt_update__gte=now-timedelta(seconds=5*60))
    elif is_online == 0:
        base_query = base_query.filter(dt_update__lt=now-timedelta(seconds=5*60))
    total = base_query.count()
    objs = base_ctl.query_objs_by_page(base_query, page_num, page_size)
    data_list = []
    for obj in objs:
        data = obj.to_dict()
        data['is_online'] = '在线' if (now - obj.dt_update).seconds < 5* 61 else '离线'
        data_list.append(data)
    data = {
        'total': total,
        'data_list': data_list,
    }
    return data


def get_user(obj_id, operator=None):
    '''
    获取用户信息
    '''
    obj = base_ctl.get_obj(UserModel, obj_id)
    data = obj.to_dict()
    return data


def get_user_base_info(obj_id, operator=None):
    '''
    获取用户信息
    '''
    obj = base_ctl.get_obj(UserModel, obj_id)
    data = {
        'data_list': base_ctl.get_obj_base_info(obj),
        'bag': get_user_bag(obj.id),
        'bank': get_user_bank(obj.id),
        'body': get_user_body(obj.id),
        'skill': get_user_skill(obj.id),
    }
    return data

def is_exists_user(name):
    '''
    判断是不是自己人
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    if user_obj:
        return True
    return False

def get_user_task(name):
    '''
    获取角色任务，暂时通过一个字段来记录，以后需要修改成工作流
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    return user_obj.task

def get_next_user(name, account_type, action):
    '''
    account_type：证类型，例如：金币证
    action: 行为，分两种：收、发
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    master_ids= AccountModel.objects.filter(typ=account_type).values_list('master_id', flat=True).all()
    if account_type == '金币':
        return get_next_gold_user(name, user_obj.zone, master_ids, action)
    else:
        return get_next_goods_user(name, user_obj.zone, master_ids, account_type, action)

def get_next_gold_user(name, zone, master_ids, action):
    '''
    金币证
    '''
    now = time_utils.now()
    if action == '发':
        online_user_slave_ids = UserModel.objects.filter(master_id__in=master_ids).filter(zone=zone).filter(dt_update__gte=now-timedelta(seconds=5*60)).values_list('slave_id', flat=True).all()
        online_user_slave_ids = list(set(list(online_user_slave_ids)))
        data = UserModel.objects.filter(master_id__in=master_ids).filter(zone=zone).exclude(name=name).exclude(slave_id__in=online_user_slave_ids)\
            .values('id', 'bag_money', 'bank_money')\
            .annotate(money=F('bag_money')+F('bank_money'))\
            .filter(money__gte=1000 * 1000).order_by('id').first()
        if data:
            user_obj = UserModel.objects.filter(id=data.get('id')).first()
            return user_obj.to_dict()
    elif action == '收':
        online_user_slave_ids = UserModel.objects.filter(master_id__in=master_ids).filter(zone=zone).filter(dt_update__gte=now-timedelta(seconds=5*60)).values_list('slave_id', flat=True).all()
        online_user_slave_ids = list(set(list(online_user_slave_ids)))
        data = UserModel.objects.filter(master_id__in=master_ids).exclude(name=name).exclude(slave_id__in=online_user_slave_ids)\
            .values('id', 'bag_money', 'bank_money')\
            .annotate(money=F('bag_money')+F('bank_money'))\
            .filter(money__lt=1000 * 1000).order_by('id').first()
        if data:
            user_obj = UserModel.objects.filter(id=data.get('id')).first()
            return user_obj.to_dict()

def get_next_goods_user(name, zone, master_ids, account_type, action):
    '''
    物品证
    '''
    now = time_utils.now()
    if action == '发':
        online_user_slave_ids = UserModel.objects.filter(master_id__in=master_ids).filter(zone=zone).filter(dt_update__gte=now-timedelta(seconds=5*60)).values_list('slave_id', flat=True).all()
        online_user_slave_ids = list(set(list(online_user_slave_ids)))
        data = GoodsModel.objects.filter(user__master_id__in=master_ids).filter(user__zone=zone).filter(name=account_type).exclude(user__name=name).exclude(user__slave_id__in=online_user_slave_ids)\
            .values('user_id').annotate(count=Count('user_id')).filter(count__gte=20).order_by('user_id').first()
        if data:
            user_obj = UserModel.objects.filter(id=data.get('user_id')).first()
            return user_obj.to_dict()
    elif action == '收':
        exclude_user_ids = GoodsModel.objects.filter(user__master_id__in=master_ids).filter(user__zone=zone).filter(name=account_type).exclude(user__name=name)\
            .values_list('user_id', flat=True).annotate(count=Count('user_id')).filter(count__gte=20).all()
        online_user_slave_ids = UserModel.objects.filter(master_id__in=master_ids).filter(zone=zone).filter(dt_update__gte=now-timedelta(seconds=5*60)).values_list('slave_id', flat=True).all()
        # 排除子账号在线的，防止左右人物同时登录
        online_user_slave_ids = list(set(list(online_user_slave_ids)))
        user_obj_query = UserModel.objects.filter(master_id__in=master_ids).filter(zone=zone).exclude(name=name).exclude(name=None).exclude(slave_id__in=online_user_slave_ids)
        if exclude_user_ids:
            exclude_user_ids = list(set(list(exclude_user_ids)))
            user_obj_query = user_obj_query.exclude(id__in=exclude_user_ids)
        user_obj = user_obj_query.order_by('id').first()
        if user_obj:
            return user_obj.to_dict()

def get_user_account_type(name):
    '''
    获取用户证类型
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    account_obj = AccountModel.objects.filter(master_id=user_obj.master_id).first()
    return account_obj.typ

def sync_user_status(name, cga_pid, cg_pid, line):
    '''
    同步角色状态
    用于定时同步，监控角色在线状态
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    if not user_obj:
        now = time_utils.now()
        query = {
            'cga_pid': cga_pid,
            'status': UserModel.ST_DISABLE,
            'dt_update__gte': now - timedelta(hours=1),
            'name': None,
        }
        user_obj = UserModel.objects.filter(**query).first()
    if not user_obj:
        raise errors.CommonError('角色不存在')
    data = {
        'name': name,
        'cga_pid': cga_pid,
        'cg_pid': cg_pid,
        'line': line,
        'status': UserModel.ST_ENABLE,
    }
    base_ctl.update_obj(UserModel, user_obj.id, data)


@transaction.atomic
def sync_user(name, job, step, level, exp, gap, money, body=None, skill=None, bag=None, bank=None):
    '''
    同步用户
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    if not user_obj:
        return
    sync_user_base_info(user_obj.id, name, job, step, level, exp, gap, money)

    if skill and isinstance(skill.get('skill_list'), list):
        sync_user_skill(user_obj.id, skill.get('skill_list'))

    if body and isinstance(body.get('goods_list'), list):
        sync_user_body(user_obj.id, body.get('goods_list'))

    if bag and isinstance(bag.get('goods_list'), list) and isinstance(bag.get('pet_list'), list):
        sync_user_bag(user_obj.id, bag.get('goods_list'), bag.get('pet_list'))

    if bank and isinstance(bank.get('goods_list'), list) and isinstance(bank.get('pet_list'), list):
        sync_user_bank(user_obj.id, bank.get('goods_list'), bank.get('pet_list'), bank.get('money'))


def sync_user_base_info(user_id, name, job, step, level, exp, gap, money):
    data = {
        'name': name,
        'job': job,
        'step': step,
        'level': level,
        'exp': exp,
        'gap': gap,
        'bag_money': money,
    }
    base_ctl.update_obj(UserModel, user_id, data)


def sync_user_skill(user_id, skill_list):
    '''
    同步用户技能
    '''
    # 先删除原来的
    query = {
        'user_id': user_id,
    }
    SkillModel.objects.filter(**query).delete()

    # 再创建新的
    skills = []
    for data in skill_list:
        data['user_id'] = user_id
        skills.append(data)
    base_ctl.create_objs(SkillModel, skills)


def sync_user_body(user_id, goods_list):
    '''
    同步用户身体
    '''
    create_goods(user_id, GoodsModel.TYP_BODY, goods_list)


def sync_user_bag(user_id, goods_list, pet_list):
    '''
    同步用户背包
    '''
    create_goods(user_id, GoodsModel.TYP_BAG, goods_list)
    create_pets(user_id, PetModel.TYP_BAG, pet_list)


def sync_user_bank(user_id, goods_list, pet_list, money):
    '''
    同步银行数据
    '''
    create_goods(user_id, GoodsModel.TYP_BANK, goods_list)
    create_pets(user_id, PetModel.TYP_BANK, pet_list)
    data = {
        'bank_money': money,
    }
    base_ctl.update_obj(UserModel, user_id, data)


def create_pets(user_id, typ, pet_list):
    _delete_pets(user_id, typ)
    _create_pets(user_id, typ, pet_list)


def _create_pets(user_id, typ, pet_list):
    data_list = []
    for data in pet_list:
        data['typ'] = typ
        data['user_id'] = user_id
        data_list.append(data)
    base_ctl.create_objs(PetModel, data_list)


def _delete_pets(user_id, typ):
    query = {
        'user_id': user_id,
        'typ': typ,
    }
    PetModel.objects.filter(**query).delete()


def create_goods(user_id, typ, goods_list):
    _delete_goods(user_id, typ)
    _create_goods(user_id, typ, goods_list)


def _create_goods(user_id, typ, goods_list):
    data_list = []
    for data in goods_list:
        data['typ'] = typ
        data['user_id'] = user_id
        data_list.append(data)
    base_ctl.create_objs(GoodsModel, data_list)


def _delete_goods(user_id, typ):
    query = {
        'user_id': user_id,
        'typ': typ,
    }
    GoodsModel.objects.filter(**query).delete()


def get_user_skill(user_id):
    query = {
        'user_id': user_id,
    }
    objs = SkillModel.objects.filter(**query).all()
    skill_list = [obj.to_dict() for obj in objs]
    data = {
        'skill_list': skill_list,
    }
    return data


def get_user_body(user_id):
    query = {
        'user_id': user_id,
        'typ': GoodsModel.TYP_BODY,
    }
    objs = GoodsModel.objects.filter(**query).all()
    goods_list = [obj.to_dict() for obj in objs]
    data = {
        'goods_list': goods_list,
    }
    return data


def get_user_bank(user_id):
    query = {
        'user_id': user_id,
        'typ': GoodsModel.TYP_BANK,
    }
    objs = GoodsModel.objects.filter(**query).all()
    goods_list = [obj.to_dict() for obj in objs]
    query = {
        'user_id': user_id,
        'typ': PetModel.TYP_BANK,
    }
    objs = PetModel.objects.filter(**query).all()
    pet_list = [obj.to_dict() for obj in objs]
    data = {
        'pet_list': pet_list,
        'goods_list': goods_list,
    }
    return data


def get_user_bag(user_id):
    query = {
        'user_id': user_id,
        'typ': GoodsModel.TYP_BAG,
    }
    objs = GoodsModel.objects.filter(**query).all()
    goods_list = [obj.to_dict() for obj in objs]

    query = {
        'user_id': user_id,
        'typ': PetModel.TYP_BAG,
    }
    objs = PetModel.objects.filter(**query).all()
    pet_list = [obj.to_dict() for obj in objs]
    data = {
        'pet_list': pet_list,
        'goods_list': goods_list,
    }
    return data

def export_users():
    '''
    导出用户
    '''
    filename = time_utils.datetime2str_by_format(time_utils.now(), '%Y%m%d%H%M%S') + '.txt'
    users = UserModel.objects.filter(is_deleted=False).all()
    context = ''
    for user in users:
        context += ','.join([str(user.master_id), str(user.slave_id), str(user.zone), str(user.site), str(user.password), str(user.name)]) + '\n'
    with open(f'./data/{filename}', 'w', encoding='utf-8') as fp:
        fp.write(context)

def import_users(user_list):
    '''
    导入用户
    '''
    data_list = []
    for user in user_list.split('\n'):
        master_id, slave_id, zone, site, password, name = user.split(',')
        zone = int(zone)
        site = int(site)
        user_obj = UserModel.objects.filter(name=name).first()
        if user_obj:
            data = {
                'master_id': master_id,
                'slave_id': slave_id,
                'zone': zone,
                'site': site,
                'name': name,
                'password': password,
            }
            base_ctl.update_obj(UserModel, user_obj.id, data)
        else:
            user_obj = UserModel.objects.filter(master_id=master_id, slave_id=slave_id, zone=zone, site=site).first()
            if user_obj:
                continue
            data = {
                'master_id': master_id,
                'slave_id': slave_id,
                'zone': zone,
                'site': site,
                'password': password,
                'name': name,
            }
            data_list.append(data)
    base_ctl.create_objs(UserModel, data_list)


def statistics():
    user_total = UserModel.objects.filter(zone=UserModel.ZONE_CNC).count()
    money_info = UserModel.objects.filter(zone=UserModel.ZONE_CNC).aggregate(Sum('bag_money'), Sum('bank_money'))
    bag_money = money_info.get('bag_money__sum') or 0
    bank_money = money_info.get('bank_money__sum') or 0
    money = bag_money + bank_money
    jobs = UserModel.objects.filter(zone=UserModel.ZONE_CNC).values('job').annotate(count=Count('id'))
    goods_list = GoodsModel.objects.filter(user__zone=UserModel.ZONE_CNC).values('name').annotate(goods_count=Sum('count')).order_by('-goods_count')
    pet_list = PetModel.objects.filter(user__zone=UserModel.ZONE_CNC).values('real_name').annotate(count=Count('id')).order_by('-count')
    data = {
        'user_total': user_total,
        'money': money,
        'jobs': list(jobs),
        'goods_list': list(goods_list),
        'pet_list': list(pet_list),
    }
    return data


def gen_bat(user_ids, setting_file, script_file, server):
    '''
    生成bat
    '''
    dest_dir = os.path.join(settings.CGA_DIR, 'batch')
    users = UserModel.objects.all() # .filter(id__in=user_ids).all()
    filename = time_utils.datetime2str_by_format(time_utils.now(), '%Y%m%d%H%M%S') + '.bat'
    all_bat = os.path.join(dest_dir, filename)
    with open(all_bat, 'w') as afp:
        for user in users:
            tmp = f'start CGAssistant.exe -gametype={user.zone} -loginuser={user.master_id} -loginpwd={user.password} -gid={user.slave_id} -server={server} -character={user.site} -autologin -skipupdate -loadscript={script_file} -scriptautorestart -loadsettings={setting_file}'
            bat_file = os.path.join(dest_dir, f'{user.name}.bat')
            with open(bat_file, 'w') as fp:
                fp.write('cd ..\n')
                fp.write(f'{tmp}\n')
                fp.write('exit')
            afp.write(f'start {user.name}.bat\n')
            afp.write('timeout 5\n')
    run_bat(all_bat)

def run_bat(bat):
    '''
    运行bat
    '''
    dest_dir = os.path.join(settings.CGA_DIR, 'batch')
    os.chdir(dest_dir)
    Popen(f"{bat}")


def run_users(users, line, script_id, script_path, json_id, json_path, injure_stop, soul_stop, auto_restart, auto_login, skip_update, auto_change_line,
              auto_create, create_name, create_role, create_color, create_points, create_element):
    '''
    运行用户
    '''
    tmp = 'CGAssistant.exe --gametype={zone} --loginuser={master_id} --loginpwd={password} --gid={slave_id} --server={line} --character={site}'
    if injure_stop:
        tmp += ' --injuryprotect'
    if soul_stop:
        tmp += ' --soulprotect'
    if auto_login is True:
        tmp += ' --autologin'
    if auto_restart is True:
        tmp += ' --scriptautorestart'
    if skip_update is True:
        tmp += ' --skipupdate'
    if auto_change_line is True:
        tmp += ' --autochangeserver'
    if script_id:
        script_obj = ScriptModel.objects.filter(id=script_id).first()
        if script_obj:
            tmp += ' --loadscript={}'.format(script_obj.path)
    else:
        tmp += ' --loadscript={}'.format(script_path)
    if json_id:
        json_obj = SettingModel.objects.filter(id=json_id).first()
        if json_obj:
            tmp += ' --loadsettings={}'.format(json_obj.path)
    else:
        tmp += ' --loadsettings={}'.format(json_path)
    if auto_create:
        tmp += ' --autocreatechara'
        tmp += ' --createcharachara={}'.format(create_role)
        tmp += ' --createcharaeye=1'
        tmp += ' --createcharamouth=1'
        tmp += ' --createcharacolor={}'.format(create_color)
        tmp += ' --createcharapoints={}'.format(create_points)
        tmp += ' --createcharaelements={}'.format(create_element)

    user_ids = [d.get('id') for d in users]
    users = UserModel.objects.filter(id__in=user_ids).all()
    for user in users:
        server = line
        if line == 0:
            server = randint(1, 10)
        cmd = tmp.format(zone=user.zone, master_id=user.master_id, password=user.password, slave_id=user.slave_id, line=server, site=user.site, script_path=script_path, json_path=json_path)
        name = create_name + gen_name(9-len(create_name))
        cmd += ' --createcharaname={}'.format(name)
        os.chdir(settings.CGA_DIR)
        p = Popen(cmd)
        user.cga_pid = p.pid
        data = {'cga_pid': p.pid}
        base_ctl.update_obj(UserModel, user.id, data)


def stop_users(users):
    '''
    停止用户
    '''
    user_ids = [d.get('id') for d in users]
    users = UserModel.objects.filter(id__in=user_ids).all()
    for user in users:
        cmd = f'taskkill -f -pid {user.cga_pid}'
        Popen(cmd)
    sleep(1)
    for user in users:
        cmd = f'taskkill -f -pid {user.cg_pid}'
        Popen(cmd)


def parse_opt(cga_pid):
    p = Popen(f'wmic process where ProcessId={cga_pid} get CommandLine  /value', stdout=subprocess.PIPE, shell=True)
    l = p.stdout.readlines()[2]
    l = l.decode('gbk')
    l = l.split(' ')
    l = [s.strip() for s in l[1:] if s]
    opts = getopt.getopt(l, "", ["gametype=", "loginuser=", "gid=", "character="])
    print(opts)


def create_script(name, path):
    '''
    创建常用脚本
    '''
    obj = ScriptModel.objects.filter(path=path).first()
    if obj:
        raise errors.CommonError('脚本已经存在')
    data = {
        'name': name,
        'path': path,
    }
    base_ctl.create_obj(ScriptModel, data)


def update_script(obj_id, name, path):
    '''
    编辑常用脚本
    '''
    obj = base_ctl.get_obj(ScriptModel, obj_id)
    data = {
        'name': name,
        'path': path,
    }
    base_ctl.update_obj(ScriptModel, obj_id, data)


def delete_script(obj_id):
    '''
    删除常用脚本
    '''
    ScriptModel.objects.filter(id=obj_id).delete()


def get_scripts(page_num=None, page_size=None):
    '''
    获取脚本列表
    '''
    base_query = ScriptModel.objects
    total = base_query.count()
    objs = base_ctl.query_objs_by_page(base_query, page_num, page_size)
    data_list = []
    for obj in objs:
        data = obj.to_dict()
        data_list.append(data)
    data = {
        'total': total,
        'data_list': data_list,
    }
    return data


def get_script(obj_id):
    '''
    获取脚本信息
    '''
    obj = base_ctl.get_obj(ScriptModel, obj_id)
    data = obj.to_dict()
    return data



def create_duty(name, task):
    '''
    当班记录
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    if not user_obj:
        return False
    duty_obj = DutyModel.objects.filter(task=task).first()
    data = {
        'user_id': user_obj.id,
        'task': task,
    }
    if duty_obj:
        base_ctl.update_obj(DutyModel, duty_obj.id, data)
    else:
        base_ctl.create_obj(DutyModel, data)
    return True


def get_duty(task):
    '''
    获取当班记录
    '''
    duty_obj = DutyModel.objects.filter(task=task).first()
    if duty_obj:
        return duty_obj.user.name